package com.xbwang.service;

import com.xbwang.utils.WxMessageUtil;
import com.xbwang.utils.xfmodel.BigModelNew;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


/**
 * @author xbwang
 * @date 2023/9/5 14:35
 **/
@Service
public class WeChatService {
    @Value("${appId}")
    private String appId;
    @Value("${DNS_URl}")
    private String DNS_URl;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());



    public String feedbackMsg(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        String message = "success";
        //响应消息
        PrintWriter out = null;
        resp.setCharacterEncoding("utf-8");
        out = resp.getWriter();
        // 把微信返回的xml信息转义成map
        try {
            Map<String, String> xmlMessage = WxMessageUtil.xmlToMap(req);
            String fromUserName = xmlMessage.get("FromUserName"); // 这个就是你关注公众号的openId
            String toUserName = xmlMessage.get("ToUserName"); // 这个是用户微信的id
            String msgType = xmlMessage.get("MsgType"); // 消息类型(event或者text)
            String createTime = xmlMessage.get("CreateTime"); // 消息创建时间 （整型）

            logger.info("消息来自（公众号的openId）=>" + fromUserName);
            logger.info("用户微信的id=>" + toUserName);
            logger.info("消息类型为=>" + msgType);
            logger.info("消息创建时间 （整型）=>" + createTime);
            if ("event".equals(msgType)) { // 如果是事件推送
                String eventType = xmlMessage.get("Event"); // 事件类型
                if ("subscribe".equals(eventType)) { // 如果是订阅消息
                    String subscribeContent = "感谢关注";
                    //将关注的用户存入数据库

                    String subscribeReturnXml = WxMessageUtil.getWxReturnMsg(xmlMessage, subscribeContent);
                    return subscribeReturnXml;
                }
                if ("unsubscribe".equals(eventType)) {//取关

                }
                if ("SCAN".equals(eventType)) { // 如果是扫码消息
                    String scanContent = "扫码成功";
                    String scanReturnXml = WxMessageUtil.getWxReturnMsg(xmlMessage, scanContent);
                    return scanReturnXml;
                }
            }
            if ("text".equals(msgType)) { // 如果是文本消息推送
                String content = xmlMessage.get("Content"); // 接收到的消息内容
                //接入讯飞大模型回答问题
                String answer = BigModelNew.answer(content);
                String textReturnXml = WxMessageUtil.getWxReturnMsg(xmlMessage, answer);
                return textReturnXml; // 将接收到的文本消息变成xml格式再返回
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return message;
    }


}
